<template>
	<view class="page-container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<x-status-bar></x-status-bar>
			<view class="flex-center-between header-navbar">
				<x-back-btn></x-back-btn>
				<view class="u-f-40 common-title">{{ lang_common[type] }}</view>
				<view></view>
			</view>

			<!-- 分割线 -->
			<u-gap height="1" bgColor="rgba(0, 0, 0, 0.07)"></u-gap>
		</view>

		<!-- 列表 -->
		<view style="padding: 12rpx 34rpx 0;">
			<view class="container">
				<view>
					<view v-for="(item, index) in applyKeys" :key="index" class="container-card u-m-t-10 bg-white">
						<view v-if="item.type === 'input'">
							<view class="u-f-32 u-lh-44 font-medio">{{ dealTextShow(item) }}</view>
							<view class="u-m-t-10">
								<input v-model="form[item.key]" :placeholder="item.tips" />
							</view>
						</view>

						<view v-else-if="item.type === 'merchantAddress'">
							<view class="u-f-32 u-lh-44 font-medio">{{ dealTextShow(item) }}</view>
							<view class="u-m-t-10">
								<view class="flex-between" style="width: 100%;" @click="getArea">
									<view class="">{{ areaFormat || lang_address.locationTips }}</view>
									<u-icon name="right" custom-prefix="u" color="#ACACAC" size="24"></u-icon>
								</view>
							</view>
						</view>

						<view v-else-if="item.type === 'address'">
							<view class="u-f-32 u-lh-44 font-medio">{{ dealTextShow(item) }}</view>
							<view class="u-m-t-10">
								<view class="flex-between" style="width: 100%;" @click="changeAddress">
									<view class="">{{ form.address }}</view>
									<u-icon name="right" custom-prefix="u" color="#ACACAC" size="24"></u-icon>
								</view>
							</view>
						</view>

						<view v-else-if="item.type === 'image'">
							<view class="u-f-32 u-lh-44 font-medio">{{ dealTextShow(item) }}</view>
							<view class="u-m-t-10">
								<x-upload v-model="form[item.key]" :imgcut="item.max" :upload-video="false" :file-count="item.max || 9"
									@change="changeFiles(item.key, $event)" mode="aspectFill" @fail="settingValue = 'camera'"></x-upload>
							</view>
						</view>

						<view v-else-if="item.type === 'picker'" class="flex-center-between"
							@click="merchantTypeVisible = true">
							<view class="u-f-32 u-lh-44 font-medio">{{ dealTextShow(item) }}</view>
							<view class="u-m-t-10 flex-center">
								<view class="u-m-r-10">{{ merchantType || item.tips }}</view>
								<u-icon name="right" custom-prefix="u" color="#ACACAC" size="24"></u-icon>
							</view>
						</view>

						<view v-else-if="item.type === 'phone'" class="form-item u-m-t-20">
							<view class="u-f-32 u-lh-44 font-medio">{{ dealTextShow(item) }}</view>
							<view class="u-m-t-10 flex-center">
								<x-number-code @change="getAreaCode"></x-number-code>

								<!-- 手机号最长15位，以国际号码为准 -->
								<input v-model="form[item.key]" type="number" maxlength="15" style="width: 100%"
									:placeholder="lang_first.phoneNumberTips" />
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view v-if="approveStatus" class="flex-center-center u-m-t-30">
			<x-common-btn background="#FD1E43" @click="submitAction">{{ lang_common.done }}</x-common-btn>
		</view>

		<view style="padding: 30rpx  34rpx;" class="u-f-26 -lh-36 color-grew">{{ lang_comerciante.saveShopTips }}
		</view>
		<!-- 商家类型选择弹窗 -->
		<x-popup v-model="merchantTypeVisible" mode="bottom" z-index="9999999" @close="merchantTypeVisible = false">
			<view class="bg-white">
				<view v-for="(item, index) in merchantTypes" :key="index">
					<u-gap v-if="index" height="0.5" bg-color="rgba(151,151,151,.2)"></u-gap>
					<view class="u-f-30 u-lh-42 u-text-center" style="padding: 36rpx 0;width: 100%;"
						@click="changeTypeAction(item)">{{ item.title }}
					</view>
				</view>
				<!-- 分割线 -->
				<u-gap height="8" bg-color="#F5F5F5"></u-gap>
				<view class="u-f-36 u-lh-50 flex-center-center" style="padding: 32rpx 0;"
					@click="merchantTypeVisible = false">
					{{ lang_common.cancel }}
				</view>
			</view>
		</x-popup>
		
		<permission-unAuthTips v-model="settingValue"></permission-unAuthTips>
	</view>
</template>

<script>
	import { USER_TYPE } from '@/config.js'
	import areacode from '@/utils/areacode.js'
	import {
		merchantApprove,
		merchantLastApproveInfo
	} from '@/api/personal.js'
	import { merchantUpdateInfo } from '@/api/merchant/merchant.js'
	export default {
		data() {
			return {
				applyKeys: [],
				type: 'applyShop', // editShop

				merchantTypeVisible: false,

				areacodeObj: areacode.list[0],
				area: {},
				form: {},
				
				approveStatus: false,
				settingValue: ''
			}
		},
		
		computed: {
			areaFormat() {
				let str = '',
					area = this.area
				for (let key in area) {
					let item = area[key]
					item && item.title && (str = str + item.title + ',')
				}
				str && (str = str.slice(0, -1))
				return str
			},

			merchantTypes() {
				return this.$store.state.common.shopCategory || []
			},
			merchantType() {
				let result = this.merchantTypes.find(item => item.categoryId === (this.form.categoryId || '')) || {}
				return result.title
			}
		},
		// 获取类型
		onLoad({
			type
		}) {
			this.type = type
			// 初始化商家表单
			let applyKeys = [{
					key: 'logoImgUrl',
					label: '商家图标',
					tips: '请上传商家名称',
					type: 'image',
					max: 1
				},
				{
					key: 'name',
					labelKey: 'merchantName',
					label: '商家名称',
					tips: '请输入商家名称',
					type: 'input'
				},
				{
					key: 'merchantAddress',
					labelKey: 'merchantAddress',
					label: '商家地址',
					tips: '请输入商家地址',
					type: 'merchantAddress'
				},
				{
					key: 'address',
					labelKey: 'merchantDetailAddress',
					label: '商家详细地址',
					tips: '请输入商家地址',
					type: 'address'
				},
				{
					key: 'certImgUrl',
					label: '营业执照',
					tips: '请上传营业执照',
					type: 'image'
				},
				{
					key: 'categoryId',
					labelKey: 'categoryType',
					label: '商家类型',
					tips: '请选择商家类型',
					type: 'picker'
				},
				{
					key: 'contactName',
					label: '联系人',
					tips: '请输入联系人姓名',
					type: 'input'
				},
				{
					key: 'idCardNumber',
					label: '联系人身份证号码',
					tips: '请输入联系人身份证号码',
					type: 'input'
				},
				{
					key: 'phone',
					labelKey: 'merchantPhone',
					label: '联系人手机号',
					tips: '请输入手机号',
					type: 'phone'
				},
				{
					key: 'environmentImgUrls',
					label: '营业环境',
					tips: '请上传营业环境照片',
					type: 'image'
				},
			]
			this.applyKeys = applyKeys
			this.initInfo()
		},
		methods: {
			// 处理文本显示
			dealTextShow(item) {
				return this.lang_shop[item.labelKey || item.key] || ''
			},
			// 设置表单
			setForm(key, value) {
				this.$set(this.form, key, value)
			},
			// 响应国际区域回调函数
			getAreaCode(result = {}) {
				this.areacodeObj = result
			},
			// 修改地址
			changeAddress() {
				let {
					latitude,
					longitude
				} = this.form
				let str = (latitude || '') + (latitude && longitude && ',' || '') + (longitude || '')
				uni.navigateTo({
					url: '/pages/other/latlng/latlng',
					events: {
						change: (e) => {
							let [lat, lng] = e.latlng
							console.log(lat, lng)
							this.setForm('latitude', lat)
							this.setForm('longitude', lng)
							this.setForm('address', e.address)
						}
					},
					success: res => {
						res.eventChannel.emit('latlng-page', str)
					}
				})
			},
			getArea() {
				uni.navigateTo({
					url: '/pages/other/city/city',
					events: {
						change: res => {
							this.area = res
							this.setForm('merchantAddress', 'unknown')
						}
					},
					success: res => {
						res.eventChannel.emit('city-page', this.area)
					}
				})
			},
			// 图片变化后触发
			changeFiles(key, files) {
				this.setForm(key, files.map(item => item.fileUrl).join(','))
			},
			// 商家类型选择后触发
			changeTypeAction(item) {
				this.setForm('categoryId', item.categoryId)
				this.merchantTypeVisible = false
			},
			// 提交申请
			submitAction() {
				let queryObj = {}
				for (let i = 0, len = this.applyKeys.length; i < len; i++) {
					let item = this.applyKeys[i]
					let key = item.labelKey || item.key
					if (item.key === 'merchantAddress') continue;
					if (!this.form[item.key]) {
						return this.$api.msg(this.lang_shop[key + 'Tips'])
					}
					queryObj[item.key] = this.form[item.key]
				}
				this.setForm('prefixCode', this.areacodeObj.code)
				let keys = ['latitude', 'longitude', 'prefixCode']
				keys.map(item => {
					queryObj[item] = this.form[item]
				})
				if (!this.area.area) return this.$api.msg(this.lang_address.addrssTips)
				let areaObj = {}
				for (let key in this.area) {
					areaObj[key] = this.area[key].title
					areaObj[key + 'Id'] = this.area[key][key + 'Id']
				}
				queryObj = {
					...queryObj,
					...areaObj,
				}
				let queryFn = fn => fn(queryObj).then(() => {
					if (this.type === 'editShop') {
						this.$store.dispatch('updateShopInfo')
					}
					this.initInfo()
					this.$api.msg('更新成功')
					setTimeout(() => {
						this.jumpBack()
					}, 1000)
				})
				queryFn(this.type === 'applyShop' ? merchantApprove : merchantUpdateInfo)
			},
			// 初始化详情
			initInfo() {
				
				merchantLastApproveInfo({}).then((data) => {
					let { approveStatus } = data || {}
					this.$set(this, 'approveStatus', (typeof approveStatus === 'number' ? approveStatus !== 0 : !approveStatus))
					if (data) {
						let keys = [...this.applyKeys.map(item => item.key), 'latitude', 'longitude', 'prefixCode']
						let obj = {}
						keys.map(item => {
							obj[item] = data[item]
						})
						this.form = {
							...obj
						}
						this.areacodeObj = { code: this.form.prefixCode }
						let addressKeys = ['country', 'province', 'area', 'city']
						let areaObj = {}
						addressKeys.map(item => {
							areaObj[item] = {
								title: data[item],
								[item + 'Id']: data[item + 'Id']
							}
						})
						this.$set(this, 'area', areaObj)
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.container {
		background-color: #F9F9F9;

		&-header {
			border-bottom: 2rpx dashed #DADADA
		}

		&-card {
			padding: 20rpx 24rpx 24rpx;
			border-radius: 4rpx;
		}
	}

	.image {
		&-container {
			width: 140rpx;
			height: 140rpx;
			background-color: #f9f9f9;
		}
	}
</style>
